﻿using BZ.Logger;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.Model.ACMTMUR;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NDK.Module.BLL
{
    public delegate void delegateUpdateUI(MeasureProduct battery);
    public delegate void delegateUpdateNGUI(MeasureProduct battery);
    public delegate void delegateShowMsgBox();
    class ProcessData
    {
        public static event delegateUpdateUI UpdateUIEvent;
        public static event delegateUpdateNGUI UpdateNGUIEvent;

        private static int SortMeasureSize(DataItem x, DataItem y)
        {
            if (x.ID > y.ID)
                return 1;
            if (x.ID < y.ID)
                return -1;
            return 0;
        }

        /// <summary>
        /// 结果判断进行分料
        /// </summary>
        /// <param name="measureProduct"></param>
        /// <returns></returns>
        public static JUDGEMENT_RESULT PrcessData(MeasureProduct measureProduct)
        {
            DataItem FAI_RANDOM_SAMPLE = new DataItem();
            FAI_RANDOM_SAMPLE.Name = "FAI-RANDOM-SAMPLE";
            FAI_RANDOM_SAMPLE.Value = 0;
            measureProduct.MeasureData.Add(FAI_RANDOM_SAMPLE);
            //FAI_RANDOM_SAMPLE.Value = 0;

            JUDGEMENT_RESULT ret = Jugement.JugeMeasureData(ref measureProduct);

            measureProduct.MeasureData.Sort(SortMeasureSize);//按照ID排序

            List<string> res = new List<string>();
            foreach (var item in measureProduct.MeasureData)
            {
                res.Add(item.JugeResult);
            }
            if (Common.点检启动一次)
            {
                if (res.Contains("NA") || res.Contains("NG"))
                {
                    MessageBox.Show("点检完成,点检结果NG");
                }
                else
                {
                    MessageBox.Show("点检完成,点检结果OK");
                }
            }
            if (Common.isUploadMes && Common.Line != "MUR")//数据上传至MES
            {
                PublicMethod.UploadMes(measureProduct);
            }
            if (Common.UploadMESFail == true)//上传失败 
            {
                ret = JUDGEMENT_RESULT.NG;
                measureProduct.NG_FAI = "Upload Fail||" + measureProduct.NG_FAI;
            }

            #region OK品抽检功能  RANDOM_SAMPLE尺寸标记
            //DataItem FAI_RANDOM_SAMPLE = new DataItem();
            //FAI_RANDOM_SAMPLE.Name = "FAI_RANDOM_SAMPLE";
            //measureProduct.MeasureData.Add(FAI_RANDOM_SAMPLE);
            //FAI_RANDOM_SAMPLE.Value = 0;
            bool isContainNGitem = false;//是否含有配置的NG项

            if (ret == JUDGEMENT_RESULT.OK)
            {
                measureProduct.OK_NG = "OK";
                FAI_RANDOM_SAMPLE.Value = 0;//OK产品标记的值
                //抽样
                if ((Common.r_Sample.NextDouble() * 100 < Common.samplePersent) && Common.isSample == true)
                {
                    FileUtils.AppendText(@"D:\Data\Sample.csv", measureProduct.SN + "__" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + "\r\n");
                    try
                    {
                        ret = JUDGEMENT_RESULT.ORT;//返回ORT
                        FAI_RANDOM_SAMPLE.Value = 1;//抽样产品
                        Common.curSampleCount++;
                        if (Common.curSampleCount >= Common.sampleCount)//抽样数量足够关闭抽样功能
                        {
                            Common.isSample = false;
                            Common.samplePersent = 0;
                            Common.curSampleCount = 0;
                            Common.sampleCount = 0;
                        }
                    }
                    catch
                    { }
                }
            }
            else
            {
                measureProduct.OK_NG = "NG";

                if (ret == JUDGEMENT_RESULT.NG)//在上下限公差的5%以内    标记3
                {
                    FAI_RANDOM_SAMPLE.Value = 3;
                }
                else if (ret == JUDGEMENT_RESULT.EXCEPTION)//超出上下限公差的5%    标记为5
                {
                    FAI_RANDOM_SAMPLE.Value = 5;//
                }

                else if (ret == JUDGEMENT_RESULT.NA)//NA    2
                {
                    FAI_RANDOM_SAMPLE.Value = 2;
                }
            }

            if (Common.Sample_4 == true)//手动标记为4   强制可以复测
            {
                FAI_RANDOM_SAMPLE.Value = 4;
            }
            #endregion

            #region 刷新数据界面  保存数据csv  苹果上传数据
            if (ret == JUDGEMENT_RESULT.OK)
            {
                //刷新FormHome窗体
                UpdateUIEvent.BeginInvoke(measureProduct, null, null);
                //保存数据至数据库
                Common.waitingForWriteToDatabaseDataQueue.Enqueue(measureProduct);
                ////苹果系统上传
                if (Common.isUploadApple == true)
                {
                    Common.isUploadAppleNg = false;
                    Common.isAppleUploadFinish = false;
                    int timeout = 0;
                    Common.waitingForUploadAppleDataQueue.Enqueue(measureProduct);
                    while (Common.isAppleUploadFinish == false)
                    {
                        timeout++;
                        Thread.Sleep(5);
                        if (timeout >= 3000)//超时15S
                        {
                            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;//报警
                            MessageBox.Show("上传Apple超时");
                            ret = JUDGEMENT_RESULT.UpAppleErr;//放NG
                            break;
                        }
                    }
                }
                if (Common.isUploadMes && Common.Line == "MUR")
                {
                    Task.Run(() =>
                    {
                        var measure = new List<MURMeaure>();
                        List<MeasureSize> measureSizeList = Jugement.GetDatabaseInfo(measureProduct.whichBlock, measureProduct.Position);
                        foreach (var item in measureProduct.MeasureData)
                        {
                            if (measureSizeList.SingleOrDefault(x => x.SizeName == item.Name).IsShow)
                            {
                                measure.Add(new MURMeaure() { Name = item.Name, Judge = "0", Value = Math.Round(item.Value, 4).ToString() });
                            }
                        }

                        Common.MURMES.MURMESQueue.Enqueue(new MURMesInfo(Common.MURMES.Config, MesType.QCInformation)
                        {
                            RowDatas = new MURRowData()
                            {
                                Time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                                SN = measureProduct.SN.Replace("+", "%2B"),
                                MdlCode = Common.MURMES.Config.MdlCode,
                                QCCode_Product1 = Common.MURMES.Config.QCode_Product1,
                                QCCode_Product2 = Common.MURMES.Config.QCode_Product2,
                                QCCode_Block = Common.MURMES.Config.QCode_Block,
                                Pos = measureProduct.Position,
                                Judge = "0",
                                Measures = measure
                            }
                        });
                    });
                }
            }

            else if (ret == JUDGEMENT_RESULT.EMPTY)//空
            {

            }

            else
            {
                #region NG产品判断是否需要过滤
                Common.NgCount++;
                if (Common.NgNameList.Count > 0)//NG项配置为空，则监控所有尺寸，否则只监控配置的尺寸
                {
                    foreach (var item in Common.NgNameList)
                    {
                        if (measureProduct.NG_FAI.Contains(item))
                        {
                            isContainNGitem = true;
                            break;
                        }
                    }
                }
                //NG项配置不为空时
                if ((isContainNGitem && Common.NgNameList.Count > 0 && Common.NgSelectedCount < Common.NgSelectCount)//如果该产品的NG项为配置的NG项，且本次循环还未挑出足够的过滤电芯，则放OK，否则放NG
                    || isContainNGitem == false && (Common.NgNameList.Count > 0 && (Common.NgUpLimit - Common.NgCount) < (Common.NgSelectCount - Common.NgSelectedCount))) //如果到配置的NG数上限了还未挑出过滤电芯，则放OK，否则放NG && (Common.NgUpLimit - Common.NgCount - Common.NgSelectedCount) >= 0)
                {
                    Common.NgSelectedCount++;
                    Common.isCurNGCellSelected = true;
                }

                //NG项配置为空时
                if (Common.NgNameList.Count == 0)
                {
                    if (Common.NgCount > Common.NgSelectCount) //前面的NgSelectCount个NG的产品放OK
                    {

                    }
                    else
                    {
                        Common.NgSelectedCount++;
                        Common.isCurNGCellSelected = true;
                    }
                }
                #endregion

                if (Common.isCurNGCellSelected == false)//无须过滤
                {
                    //NA勾选不上传
                    if (ret == JUDGEMENT_RESULT.NA && Common.isUploadNA == true)
                    {

                    }
                    else
                    {
                        //刷新FomHome显示NG的DataGrad窗体
                        UpdateNGUIEvent.BeginInvoke(measureProduct, null, null);
                        //保存数据csv
                        Common.waitingForWriteToDatabaseDataQueue.Enqueue(measureProduct);

                        //上传苹果系统
                        if (Common.isUploadApple == true)
                        {
                            int timeout = 0;
                            Common.isAppleUploadFinish = false;
                            Common.waitingForUploadAppleDataQueue.Enqueue(measureProduct);
                            while (Common.isAppleUploadFinish == false)
                            {
                                Thread.Sleep(5);
                                if (timeout >= 3000)//超时15S 
                                {
                                    MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;//报警
                                    MessageBox.Show("上传Apple超时");
                                    break;
                                }
                            }
                        }
                        if (Common.isUploadMes && Common.Line == "MUR")
                        {
                            Task.Run(() =>
                            {
                                Common.MURMES.MURMESQueue.Enqueue(new MURMesInfo(Common.MURMES.Config, MesType.DefectInformation)
                                {
                                    Timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"),
                                    LotNo = measureProduct.SN.Replace("+", "%2B"),
                                    DefectCode = "0001",
                                    MdlCode = Common.MURMES.Config.MdlCode,
                                    Remarks = measureProduct.NG_FAI
                                });
                                var measure = new List<MURMeaure>();
                                List<MeasureSize> measureSizeList = Jugement.GetDatabaseInfo(measureProduct.whichBlock, measureProduct.Position);
                                foreach (var item in measureProduct.MeasureData)
                                {
                                    if (measureSizeList.SingleOrDefault(x => x.SizeName == item.Name).IsShow)
                                    {
                                        measure.Add(new MURMeaure() { Name = item.Name, Judge = "0", Value = Math.Round(item.Value, 4).ToString() });
                                    }
                                }
                                
                                Common.MURMES.MURMESQueue.Enqueue(new MURMesInfo(Common.MURMES.Config, MesType.QCInformation)
                                {
                                    RowDatas = new MURRowData()
                                    {
                                        Time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                                        SN = measureProduct.SN.Replace("+", "%2B"),
                                        MdlCode = Common.MURMES.Config.MdlCode,
                                        QCCode_Product1 = Common.MURMES.Config.QCode_Product1,
                                        QCCode_Product2 = Common.MURMES.Config.QCode_Product2,
                                        QCCode_Block = Common.MURMES.Config.QCode_Block,
                                        Pos = measureProduct.Position,
                                        Judge = "1",
                                        Measures = measure
                                    }
                                });
                            });
                        }
                    }

                    if (Common.NgCount >= Common.NgUpLimit)
                    {
                        Common.NgCount = 0;
                        Common.NgSelectedCount = 0;
                        Common.isSelectedNGCell = false;
                    }
                }
                else//NG过滤    不要显示，不要存数据   不上传
                {
                    Common.isCurNGCellSelected = false;
                    if (Common.NgCount >= Common.NgUpLimit)
                    {
                        Common.NgCount = 0;
                        Common.NgSelectedCount = 0;
                        Common.isSelectedNGCell = false;
                    }
                }
            }
            #endregion

            Common.MURMES.UpLoadMURMES();
            //产品强制放某个盘   测试流程用
            if (Common.isForceOK)
            {
                ret = JUDGEMENT_RESULT.OK;
            }
            if (Common.isForceNG)
            {
                ret = JUDGEMENT_RESULT.NG;
            }
            if (Common.isForceORT)
            {
                ret = JUDGEMENT_RESULT.ORT;
            }
            return ret;
        }


        private static readonly object _lock = new object();

        public static JUDGEMENT_RESULT PrcessDataTotal(MeasureProduct measureProduct)
        {

            lock (_lock)
            {

                #region 变量定义
                JUDGEMENT_RESULT ret = JUDGEMENT_RESULT.OK;
                bool bBarcodeResult = false;
                bool? rtnMES = false;

                DataItem FAI_RANDOM_SAMPLE = new DataItem(); //measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI-RANDOM-SAMPLE");
                FAI_RANDOM_SAMPLE.Name = "FAI-RANDOM-SAMPLE";
                measureProduct.MeasureData.Add(FAI_RANDOM_SAMPLE);
                FAI_RANDOM_SAMPLE.Value = 0;
                #endregion

                #region 判断二维码是否是OK的
                if ((measureProduct.SN.ToLower().Contains("Test") || measureProduct.SN.Contains("NA")) && measureProduct.SN.Length < 7) //二维码识别不到的放入NG
                {
                    measureProduct.SN = "Test";
                    measureProduct.NG_FAI += ("SN Fail" + @"\");
                    bBarcodeResult = false;
                }
                else
                {
                    bBarcodeResult = true;
                }
                #endregion

                #region MacMini上传
                bool retMacmini = false;
                if (Common.isUploadApple && measureProduct.SN != "Test")
                {
                    retMacmini = UploadMacMini(measureProduct);
                }
                #endregion

                #region MES上传
                if (Common.isUploadMes)
                {
                    try
                    {
                        if (SMPMesUpload.SMPInsiteCheck(measureProduct.SN))                //1.检索二维码信息，如果该产品没问题再进行
                        {
                            rtnMES = UploadMES(measureProduct);
                        }
                        else
                        {
                            rtnMES = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.AppendUiLog.Log("上传MES检查二维码函数“SMPInsiteCheck”执行异常!" + ex.ToString(), LogType.Error);
                        rtnMES = null;
                    }
                }
                #endregion

                #region 综合判断最终产品结果
                if (Common.rtnDataResult_PPG == JUDGEMENT_RESULT.NG || Common.rtnDataResult_Vision == JUDGEMENT_RESULT.NG) //优先级数据NG > 数据EXCEPT > 数据NA >二维码NG >上传NG
                {
                    ret = JUDGEMENT_RESULT.NG;
                }
                else if (Common.rtnDataResult_PPG == JUDGEMENT_RESULT.EXCEPTION || Common.rtnDataResult_Vision == JUDGEMENT_RESULT.EXCEPTION)
                {
                    ret = JUDGEMENT_RESULT.EXCEPTION;
                }
                else if (Common.rtnDataResult_PPG == JUDGEMENT_RESULT.NA || Common.rtnDataResult_Vision == JUDGEMENT_RESULT.NA)
                {
                    ret = JUDGEMENT_RESULT.NA;
                }

                if (!bBarcodeResult || !retMacmini) //二维码错误或者上传Macmini错误
                {
                    if (ret != JUDGEMENT_RESULT.EXCEPTION && ret != JUDGEMENT_RESULT.NA) ret = JUDGEMENT_RESULT.NG;
                }

                if (rtnMES != true) //MES上传错误
                {
                    if (ret != JUDGEMENT_RESULT.EXCEPTION && ret != JUDGEMENT_RESULT.NA) ret = JUDGEMENT_RESULT.NG;
                    if (rtnMES == null)//上传二维码校验该产品Outoff Line
                    {
                        measureProduct.NG_FAI = "SNOutStation||" + measureProduct.NG_FAI;
                    }
                }
                #endregion

                #region OK品抽检功能  RANDOM_SAMPLE尺寸标记
                if (ret == JUDGEMENT_RESULT.OK)
                {
                    measureProduct.OK_NG = "OK";
                    FAI_RANDOM_SAMPLE.Value = 0;//OK产品标记的值
                                                //抽样
                    if ((Common.r_Sample.NextDouble() * 100 < Common.samplePersent) && Common.isSample == true)
                    {
                        FileUtils.AppendText(@"D:\Data\Sample.csv", measureProduct.SN + "__" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + "\r\n");
                        try
                        {
                            ret = JUDGEMENT_RESULT.ORT;//返回ORT
                            FAI_RANDOM_SAMPLE.Value = 1;//抽样产品
                            Common.curSampleCount++;
                            if (Common.curSampleCount >= Common.sampleCount)//抽样数量足够关闭抽样功能
                            {
                                Common.isSample = false;
                                Common.samplePersent = 0;
                                Common.curSampleCount = 0;
                                Common.sampleCount = 0;
                            }
                        }
                        catch
                        { }
                    }
                }
                else
                {
                    measureProduct.OK_NG = "NG";

                    if (ret == JUDGEMENT_RESULT.NG)//在上下限公差的5%以内    标记3
                    {
                        FAI_RANDOM_SAMPLE.Value = 3;
                    }
                    else if (ret == JUDGEMENT_RESULT.EXCEPTION)//超出上下限公差的5%    标记为5
                    {
                        FAI_RANDOM_SAMPLE.Value = 5;//
                    }
                    else if (ret == JUDGEMENT_RESULT.NA)//NA    2
                    {
                        FAI_RANDOM_SAMPLE.Value = 2;
                    }
                }

                if (Common.Sample_4 == true)//手动标记为4   强制可以复测
                {
                    FAI_RANDOM_SAMPLE.Value = 4;
                }
                #endregion

                #region 刷新数据界面  保存数据csv
                if (ret == JUDGEMENT_RESULT.OK)
                {
                    //刷新FormHome窗体
                    UpdateUIEvent.BeginInvoke(measureProduct, null, null);
                    //保存数据至数据库
                    Common.waitingForWriteToDatabaseDataQueue.Enqueue(measureProduct);
                }
                else
                {
                    //刷新FomHome显示NG的DataGrad窗体
                    UpdateNGUIEvent.BeginInvoke(measureProduct, null, null);
                    //保存数据csv
                    Common.waitingForWriteToDatabaseDataQueue.Enqueue(measureProduct);
                }
                #endregion

                return ret;
            }
        }

        private static bool UploadMacMini(MeasureProduct measureProduct)
        {
            bool ret = true;

            string str_SendToApple = string.Empty;
            try
            {

                string appleQrSN = measureProduct.SN.Split('+')[0];

                str_SendToApple += "_{" + "\n";
                str_SendToApple += appleQrSN + "@start" + "\n";

                //尺寸提取及整合
                MeasureSizeServices measureSizeServices = new MeasureSizeServices();
                List<MeasureSize> measureSizeList = measureSizeServices.GetAllByProjectNameAndTurnNum(Common.ProjectName, 0);
                foreach (DataItem cameraData in measureProduct.MeasureData)//遍历所有尺寸var cameraData in battery.MeasureData
                {
                    MeasureSize measureSizeUploadApple = measureSizeList.SingleOrDefault(size => size.SizeName == cameraData.Name);

                    if (measureSizeUploadApple == null)
                    {
                        continue;//如果该工程下没有这个尺寸，放弃上传
                    }
                    if (measureSizeUploadApple.IsShow == false) continue;//如果该尺寸号不需要显示，放弃上传

                    if (cameraData.Name == "FAI-RANDOM-SAMPLE")
                    {
                        continue;
                    }

                    string appleValue = cameraData.Value.ToString("0.000");
                    string Uppervalue = (measureSizeUploadApple.NormValue + measureSizeUploadApple.UpperDeviation).ToString();
                    string LowerValue = (measureSizeUploadApple.NormValue - measureSizeUploadApple.LowerDeviation).ToString();

                    if (measureSizeUploadApple.IsJudging == false)  //
                    {

                        if (cameraData.Value > 500 || cameraData.Value < -500)
                        {
                            str_SendToApple += appleQrSN
                                                        + "@pdata"
                                                        + "@" + cameraData.Name
                                                        + "@" + "NA"
                                                        + "@" + "NA"
                                                        + "@" + "NA"
                                                        + "@" + "mm" + "\n"; //+Environment.NewLine;
                        }
                        else
                        {
                            str_SendToApple += appleQrSN
                                                        + "@pdata"
                                                        + "@" + cameraData.Name
                                                        + "@" + appleValue
                                                        + "@" + "NA"
                                                        + "@" + "NA"
                                                        + "@" + "mm" + "\n"; //+Environment.NewLine;
                        }


                    }
                    else
                    {
                        if (Common.isForceOK == true)//强制OK不需要再修改为99999
                        {
                            Uppervalue = "NA";
                            LowerValue = "NA";
                        }

                        if (cameraData.Value > 500 || cameraData.Value < -500)
                        {
                            str_SendToApple += appleQrSN
                                                        + "@pdata"
                                                        + "@" + cameraData.Name
                                                        + "@" + "NA"
                                                        + "@" + LowerValue
                                                        + "@" + Uppervalue
                                                        + "@" + "mm" + "\n"; //+ Environment.NewLine;
                        }
                        else
                        {
                            str_SendToApple += appleQrSN
                                                        + "@pdata"
                                                        + "@" + cameraData.Name
                                                        + "@" + appleValue
                                                        + "@" + LowerValue
                                                        + "@" + Uppervalue
                                                        + "@" + "mm" + "\n"; //+ Environment.NewLine;
                        }
                    }
                }

                //FAI_RANDOM_SAMPLE
                DataItem FAI_RANDOM_SAMPLE = measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI-RANDOM-SAMPLE");

                str_SendToApple += appleQrSN
                                            + "@pdata"
                                            + "@" + FAI_RANDOM_SAMPLE.Name
                                            + "@" + FAI_RANDOM_SAMPLE.Value.ToString()
                                            + "@" + "NA"
                                            + "@" + "NA"
                                            + "@" + "mm" + "\n"; //Environment.NewLine;


                //结束语
                str_SendToApple += appleQrSN + "@" + "submit@NDKMeasurement_" + Common.currentVersion + "\n"; // Environment.NewLine;

                //加入结束符
                str_SendToApple += "}" + "\n"; //Environment.NewLine;
                appleQrSN = "";
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log("上传数据整合异常!" + ex.ToString(), LogType.Error);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                if (MessageBox.Show("上传数据整合异常!" + ex.ToString()) == DialogResult.OK)
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
                else
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
            }

            int SendErrCount = 0;
        SendApple:
            //发送字符串
            try
            {
                Common.AsyncClient_MacMini.SendAsync(str_SendToApple);
                WriteLogToTxt(str_SendToApple);

                //等待MacMini回复上传Ok信号
                Stopwatch sw = new Stopwatch();
                sw.Restart();
                while (true)
                {
                    if (Common.AsyncRcvMsgFromMacMini == "MacMiniOk")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log("上传数据到MacMini成功", LogType.Info);
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniNg")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log("上传数据到MacMini失败!", LogType.Error);

                        ret = false;
                        measureProduct.NG_FAI = "UploadAppleNG" + "||" + measureProduct.NG_FAI;
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniErr")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log("MacMini未过站，排出！", LogType.Error);

                        ret = false;
                        measureProduct.NG_FAI = "UploadApple AE-1_Fail" + "||" + measureProduct.NG_FAI;
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniErrWithoutStart")
                    {
                        SendErrCount++;
                        Common.AsyncRcvMsgFromMacMini = "";

                        if (SendErrCount < 3)
                        {
                            //发送二维码信息
                            string send = string.Empty;
                            string appleQrSN = measureProduct.SN.Split('+')[0];

                            send += appleQrSN + "@start" + "\n";

                            Common.AsyncClient_MacMini.SendAsync(send);
                            WriteLogToTxt(send);

                            goto SendApple;
                        }
                        else
                        {
                            Common.AppendUiLog.Log("MacMini上传异常，请检查接收端Log异常信息！", LogType.Error);

                            ret = false;
                            measureProduct.NG_FAI = "UploadApple AE-1_Fail" + "||" + measureProduct.NG_FAI;
                            break;
                        }
                    }
                    else
                    {
                        if (sw.ElapsedMilliseconds > 8000)
                        {
                            sw.Reset();
                            sw.Stop();

                            ret = false;
                            measureProduct.NG_FAI = "UploadAppleTimeOut" + "||" + measureProduct.NG_FAI;
                            Common.AppendUiLog.Log("接收MacMini回传超时!", LogType.Error);
                            WriteLogToTxt("接收MacMini回传超时!" + "\r\n");

                            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                            if (MessageBox.Show("接收MacMini回传超时! 请检查MacMini是否正常！") == DialogResult.OK)
                            {
                                MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                            }
                            else
                            {
                                MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                            }

                            break;
                        }
                    }

                    Thread.Sleep(10);
                }
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log("上传数据到MacMini异常!" + ex.ToString(), LogType.Error);
                WriteLogToTxt("上传数据到MacMini异常!" + ex.ToString() + "\r\n");
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                if (MessageBox.Show("上传数据到MacMini异常!" + ex.ToString()) == DialogResult.OK)
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
                else
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }

                ret = false;
                measureProduct.NG_FAI = "UploadAppleAbnormal" + "||" + measureProduct.NG_FAI;
            }
            return ret;
        }

        private static bool UploadMES(MeasureProduct measureProduct)
        {
            bool ret = true;
            try
            {
                List<string> paramFAIUploadMes = new List<string>();
                MeasureSizeServices measureSizeServices = new MeasureSizeServices();

                foreach (var cameraData in measureProduct.MeasureData)//遍历所有尺寸
                {
                    MeasureSize measureSizeUploadMes = measureSizeServices.GetModelByProjectNameAndSizeName(Common.ProjectName, cameraData.Name);
                    if (measureSizeUploadMes == null) continue;//如果该工程下没有这个尺寸，放弃上传
                    if (measureSizeUploadMes.IsShow == false) continue;//如果该尺寸号不需要显示，放弃上传
                                                                       //if (measureSizeUploadMes.IsJudging == false) continue;//如果该尺寸号不需要判定，放弃上传
                                                                       //if (measureSizeUploadMes.SizeName == "FAI-RANDOM-SAMPLE") continue;//如果该尺寸号是抽检标记，放弃上传
                    string mesValue = /*cameraData.Name + ":" +*/ cameraData.Value.ToString("0.000");
                    paramFAIUploadMes.Add(mesValue);
                }

                if (Common.bTotalResult) measureProduct.OK_NG = "OK";
                else measureProduct.OK_NG = "NG";

                bool flagUploadResult = false;
                flagUploadResult = SMPMesUpload.SMPMesData_Collection_Auto(measureProduct, paramFAIUploadMes.ToArray());

                if (!flagUploadResult)//上传失败
                {
                    ret = false;
                    measureProduct.NG_FAI = "MesUpload Fail||" + measureProduct.NG_FAI;
                }
            }
            catch (Exception xxx)
            {
                Common.AppendUiLog.Log(measureProduct.SN + " :上传异常：" + xxx.ToString(), LogType.Error);
                measureProduct.NG_FAI = "MesUpload Fail||" + measureProduct.NG_FAI;
                ret = false;
            }
            return ret;
        }

        private static readonly object LogLock = new object();
        private static void WriteLogToTxt(string strLog)
        {
            lock (LogLock)
            {
                String System_Now_Time = null;
                String File_Create_Time = null;

                System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
                File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
                string logDocument = File_Create_Time + ".txt";

                string str = Process.GetCurrentProcess().MainModule.FileName;
                string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\SendInfoLogMacMini";
                if (!Directory.Exists(logFilePath))
                {
                    Directory.CreateDirectory(logFilePath);
                }
                logFilePath = logFilePath + "//" + logDocument;
                FileStream fs = new FileStream(logFilePath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(System_Now_Time + ":   " + strLog);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }
    }
}

